{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3b4bc124",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "60b1fd50",
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import LlamaConfig, LlamaForCausalLM, AutoTokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "45d866e5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaConfig {\n",
       "  \"_name_or_path\": \"fpf-1.1b-instructions-16k-call-v2/checkpoint-9000\",\n",
       "  \"architectures\": [\n",
       "    \"LlamaForCausalLM\"\n",
       "  ],\n",
       "  \"attention_bias\": false,\n",
       "  \"attention_dropout\": 0.0,\n",
       "  \"bos_token_id\": 1,\n",
       "  \"eos_token_id\": 2,\n",
       "  \"hidden_act\": \"silu\",\n",
       "  \"hidden_size\": 2048,\n",
       "  \"initializer_range\": 0.02,\n",
       "  \"intermediate_size\": 5632,\n",
       "  \"max_position_embeddings\": 32768,\n",
       "  \"model_type\": \"llama\",\n",
       "  \"num_attention_heads\": 32,\n",
       "  \"num_hidden_layers\": 10,\n",
       "  \"num_key_value_heads\": 4,\n",
       "  \"pretraining_tp\": 1,\n",
       "  \"rms_norm_eps\": 1e-05,\n",
       "  \"rope_scaling\": null,\n",
       "  \"rope_theta\": 10000.0,\n",
       "  \"tie_word_embeddings\": false,\n",
       "  \"torch_dtype\": \"bfloat16\",\n",
       "  \"transformers_version\": \"4.36.2\",\n",
       "  \"use_cache\": true,\n",
       "  \"vocab_size\": 32000\n",
       "}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "half_config = LlamaConfig.from_pretrained('mesolitica/malaysian-tinyllama-1.1b-16k-instructions-v3', \n",
    "                                             num_hidden_layers = 10)\n",
    "half_config"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e8e56f66",
   "metadata": {},
   "outputs": [],
   "source": [
    "small = LlamaForCausalLM(half_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e81a5693",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "571516928"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(p.numel() for p in small.parameters())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "b81d770e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0aaa370cbb404ef7b3c2cc01396cb4b2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "model.safetensors:   0%|          | 0.00/2.20G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "37a29034df0746da8cef83aec64e9405",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "generation_config.json:   0%|          | 0.00/124 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "model = LlamaForCausalLM.from_pretrained('mesolitica/malaysian-tinyllama-1.1b-16k-instructions-v3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6422b189",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LlamaForCausalLM(\n",
       "  (model): LlamaModel(\n",
       "    (embed_tokens): Embedding(32000, 2048)\n",
       "    (layers): ModuleList(\n",
       "      (0-21): 22 x LlamaDecoderLayer(\n",
       "        (self_attn): LlamaSdpaAttention(\n",
       "          (q_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
       "          (k_proj): Linear(in_features=2048, out_features=256, bias=False)\n",
       "          (v_proj): Linear(in_features=2048, out_features=256, bias=False)\n",
       "          (o_proj): Linear(in_features=2048, out_features=2048, bias=False)\n",
       "          (rotary_emb): LlamaRotaryEmbedding()\n",
       "        )\n",
       "        (mlp): LlamaMLP(\n",
       "          (gate_proj): Linear(in_features=2048, out_features=5632, bias=False)\n",
       "          (up_proj): Linear(in_features=2048, out_features=5632, bias=False)\n",
       "          (down_proj): Linear(in_features=5632, out_features=2048, bias=False)\n",
       "          (act_fn): SiLU()\n",
       "        )\n",
       "        (input_layernorm): LlamaRMSNorm()\n",
       "        (post_attention_layernorm): LlamaRMSNorm()\n",
       "      )\n",
       "    )\n",
       "    (norm): LlamaRMSNorm()\n",
       "  )\n",
       "  (lm_head): Linear(in_features=2048, out_features=32000, bias=False)\n",
       ")"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6f406046",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(range(22))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "e049a348",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.nn as nn\n",
    "\n",
    "def copy_layers(src_layers, dest_layers, layers_to_copy):\n",
    "    layers_to_copy = nn.ModuleList([src_layers[i] for i in layers_to_copy])\n",
    "    assert len(dest_layers) == len(layers_to_copy), f\"{len(dest_layers)} != {len(layers_to_copy)}\"\n",
    "    dest_layers.load_state_dict(layers_to_copy.state_dict())\n",
    "\n",
    "layers_to_copy = [0,1,2,3,4,17,18,19,20,21]\n",
    "\n",
    "copy_layers(model.model.layers, small.model.layers, layers_to_copy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "65a328f1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.embed_tokens.load_state_dict(model.model.embed_tokens.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "17006ed0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.model.norm.load_state_dict(model.model.norm.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2e2c21a7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<All keys matched successfully>"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.lm_head.load_state_dict(model.lm_head.state_dict())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "ca6e7761",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "small = small.type(torch.bfloat16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "da047413",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "0361d9423bdc4f9bb849199b415366c2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "model.safetensors:   0%|          | 0.00/1.14G [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/huseinzol05/570M-tinyllama/commit/c7cf99f56206b8f4a9693baf325506597a3ed36c', commit_message='Upload LlamaForCausalLM', commit_description='', oid='c7cf99f56206b8f4a9693baf325506597a3ed36c', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "small.push_to_hub('huseinzol05/570M-tinyllama')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "dda90989",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a3390071f9d746b0a2421f71478a84dc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer_config.json:   0%|          | 0.00/1.42k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "099dd66096b54b42b20e6b827fdc839a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "tokenizer.json:   0%|          | 0.00/1.84M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "60f555dd91bf47fcb94698de5c764cd5",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "special_tokens_map.json:   0%|          | 0.00/552 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tokenizer = AutoTokenizer.from_pretrained('mesolitica/malaysian-tinyllama-1.1b-16k-instructions-v3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "9d65b213",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "CommitInfo(commit_url='https://huggingface.co/huseinzol05/570M-tinyllama/commit/4487f41db06a786f861381468c41695b1a5cf56a', commit_message='Upload tokenizer', commit_description='', oid='4487f41db06a786f861381468c41695b1a5cf56a', pr_url=None, pr_revision=None, pr_num=None)"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.push_to_hub('huseinzol05/570M-tinyllama')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
